<template>
  <div class="app-container">
    <div class="search-container" ref="search"></div>
    <el-card shadow="never">
      <template #header>
        <el-button size="default" type="primary" @click="addQrCode">生成二维码</el-button>
        <el-button @click="hanldeDelete" size="default" type="danger">批量删除</el-button>
        <div class="red">
          <div>
            《中华人民共和国消防法》第十七条规定，消防安全重点单位除应当履行本法第十六条规定的职责外，还应当履行下列消防安全职责：（三）实行每日防火巡查，并建立巡查记录。《机关、团体、企业、事业单位消防安全管理规定》消防安全重点单位应当进行每日防火巡查，并确定巡查的人员、内容、部位和频次。公众聚集场所在营业期间的防火巡查应当至少每二小时一次；营业结束时应当对营业现场进行检查，消除遗留火种。
          </div>
        </div>
      </template>
      <el-table
        :height="pageHeight + 'px'"
        :data="tableData"
        v-loading="tableDataLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="是否绑定" prop="status" :formatter="qrCodeStatus"></el-table-column>
        <el-table-column label="创建时间" prop="update_time" :formatter="formatterTime"></el-table-column>
        <el-table-column label="url" prop="url">
          <template #default="scope">
            <el-button style="color: #409eff" type="text" @click="handleCopyLink(scope.row)">复制URL</el-button>
          </template>
        </el-table-column>
        <el-table-column label="二维码" prop="qr_src">
          <template #default="scope">
            <div class="qr-wrapper" @click="showQrCodeDetail(scope.row)">
              <img :src="upDataUrl + scope.row.src" class="qr-img" />
              <span class="qr-tip">点击查看</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @current-change="handleCurrentChange"
          v-model:currentPage="tableDataInfo.page"
          :page-count="tableDataInfo.total_page"
          layout="prev, pager, next, jumper"
          background
        >
          <!-- :hide-on-single-page="true" -->
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      v-model="dialogFormVisible"
      destroy-on-close
      width="30%"
      @close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form ref="childForm" :rules="rules" :model="formData" label-position="top">
        <el-row>
          <el-col :span="6" :offset="6">
            <el-form-item label="二维码张数" prop="number">
              <!-- <el-input v-model="formData.number"></el-input> -->
              <el-input-number v-model="formData.number" :min="1" label="描述文字"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="qrModalVisible" width="18%" :center="true" :close-on-click-modal="false">
      <div class="qr-modal-wrapper" ref="qrImg">
        <img :src="qrModalData.qrSrc" class="qr-modal-img" />
        <span>{{ qrModalData.qrCode }}</span>
      </div>
      <div class="qr-modal-download">
        <el-button type="primary" @click="downloadQrImg">点击下载</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import storage from '@/util/storage'
import html2canvas from 'html2canvas'
import { ElMessage } from 'element-plus'
export default {
  data() {
    return {
      tableData: [],
      tableDataLoading: false,
      tableDataInfo: '',
      fatherId: '',
      dialogFormVisible: false,
      formData: {
        number: 10,
        unit_id: ''
      },
      rules: {
        number: [{ required: true, message: '请输入', trigger: 'blur' }],
        unit_id: [{ required: true, message: '请选择', trigger: 'blur' }]
      },
      id: '',
      unitLists: [],
      qrModalVisible: false,
      qrModalData: {},
      upDataUrl: import.meta.env.DEV ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
      pageHeight: 0,
      ids: []
    }
  },
  computed: {
    upLoadImgHeader() {
      return {
        'A-Token': this.$store.state.user.a_token,
        'U-Token': this.$store.state.user.u_token
      }
    }
  },
  created() {
    this.fatherId = this.$route.query.id
    if (this.$route.query.from) this.from = this.$route.query.from
    if (this.$route.query.unitIdFromChild) this.unitIdFromChild = this.$route.query.unitIdFromChild
    this.formData.unit_id = this.$route.query.id
    this.getLists()
  },
  mounted() {
    this.pageHeight = window.innerHeight - this.$refs.search.clientHeight - 310
  },
  methods: {
    hanldeDelete() {
      if (this.ids.length == 0) {
        this.$message({
          message: '请选择要删除的数据',
          type: 'warning'
        })
        return
      }
      this.$confirm('你确定删除这些数据吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$api
            .post('/unit/QrCode/batchDeletion', {
              ids: this.ids
            })
            .then((res) => {
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.getLists()
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 批量删除id
    handleSelectionChange(row) {
      this.ids = row.map((item) => item.id)
    },
    formatterTime(row, column, cellValue, index) {
      return this.$getDateTime(cellValue)
    },
    handleCurrentChange(e) {
      this.getLists(e)
    },
    // 复制
    handleCopyLink(row) {
      console.log(row.url)
      let _this = this
      console.log(this)
      _this.$copyText(row.url).then(
        function (e) {
          _this.$message({
            showClose: true,
            message: '复制成功',
            type: 'success'
          })
        },
        function (e) {
          _this.$message({
            showClose: true,
            message: '复制失败，请手动复制',
            type: 'error'
          })
        }
      )
    },
    downloadQrImg() {
      let that = this
      html2canvas(that.$refs.qrImg, {
        useCORS: true
      }).then((canvas) => {
        let _url = canvas.toDataURL('image/png')
        let a = document.createElement('a')
        a.href = _url
        a.download = '二维码'
        a.click()
      })
    },
    showQrCodeDetail(data) {
      console.log(data)
      let that = this
      this.qrModalVisible = true
      this.$api
        .post('/index/Qrcode/getBase64', {
          src: data.src
        })
        .then((res) => {
          that.qrModalData = {
            qrSrc: res.data,
            qrCode: data.qr_code_no,
            name: data.name
          }
          // if(that.from !== 'unit_child') {//子单位
          //   that.qrModalData.unitName = data.unit_name;
          // }else{
          //   that.qrModalData.unitName = data.sub_unit_name;
          // }
        })
    },
    qrCodeStatus(row, column, cellValue, index) {
      let temp = ['', '待绑定', '已绑定']
      return temp[cellValue]
    },
    getLists(page) {
      this.tableDataLoading = true
      let pageNum = 1
      if (page) {
        pageNum = page
      }
      let user_info = this.$store.state.user.user_info
      let query = {
        region_id: user_info.region_id,
        page: pageNum,
        rows: 13
      }
      if (this.from === 'unit_child') {
        query.unit_id = this.unitIdFromChild
        query.sub_unit_id = this.fatherId
      } else {
        query.unit_id = this.fatherId
      }
      this.$api
        .post('/unit/QrCode/lists', query)
        .then((res) => {
          this.tableData = res.data.lists
          this.tableDataInfo = res.data
        })
        .finally(() => {
          this.tableDataLoading = false
        })
    },
    addQrCode() {
      this.dialogFormVisible = true
    },
    closeDialog() {
      this.$refs.childForm.resetFields()
      let temp = this.formData
      for (let key in temp) {
        temp[key] = ''
      }
      this.formData = temp
    },
    submitForm() {
      this.$refs.childForm.validate((valid) => {
        if (valid) {
          let data = this.formData
          data.unit_id = this.fatherId
          console.log(data)
          this.$api.post('/unit/QrCode/create', data).then(() => {
            this.getLists()
            this.dialogFormVisible = false
          })
        } else {
          ElMessage.error('请填写完整')
          return false
        }
      })
    }
  }
}
</script>
<style scoped>

.red{
  color: red;
  font-size: 14px;
  margin-top: 10px;
}

.block {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

.qr-wrapper {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  cursor: pointer;
}

.qr-img {
  width: 80px;
  height: 80px;
}

.qr-tip {
  width: 80px;
  text-align: center;
}

.qr-tip:hover {
  color: #5482ee;
  text-decoration: underline;
}

.qr-modal-wrapper {
  display: flex;
  justify-content: space-around;
  flex-direction: column;
  padding: 30px 0;
}

.qr-modal-wrapper span {
  display: flex;
  justify-content: space-around;
  align-items: center;
  line-height: 24px;
}

.qr-modal-img {
  width: 200px;
  height: 200px;
  margin: 0 auto;
}

.qr-modal-download {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 30px;
}
</style>
